import { updateQueue } from './component';

// 事件委托，所有事件绑定到document上
export function addEvent(dom, eventType, handler) {
    let store = dom.store || (dom.store = {});
    // store.onclick = handler
    store[eventType] = handler; 
    // 同一事件只绑定一次
    if (!document[eventType]) {
        // 用addEventListener需要把on去掉
        // eventType = eventType.slice(2);
        // document.addEventListener(eventType, dispatchEvent);
        document[eventType] = dispatchEvent;
    }
}

function dispatchEvent(event) {
    let { target, type } = event;
    let eventType = `on${type}`;
    // 开启批量更新
    updateQueue.isBatchingUpdate = true;
    // 合成事件
    let syntheticEvent = createSyntheticEvent(event);
    // 模拟事件冒泡，找到绑定事件元素，调用事件处理函数
    while(target) {
        let { store } = target;
        let handler = store && store[eventType];
        handler && handler.call(target, syntheticEvent);
        target = target.parentNode;
    }
    // 关闭批量更新
    updateQueue.isBatchingUpdate = false;
    // 调用更新函数
    updateQueue.batchUpdate();
}

// 合成事件：兼容性处理，事件包装
function createSyntheticEvent(event) {
    let syntheticEvent = {};
    for (let key in event) {
        syntheticEvent[key] = event;
    }
    return syntheticEvent;
}